package com.yboot.module.quartz.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yboot.module.quartz.model.dto.SysJobDto;
import com.yboot.module.quartz.model.entity.SysJobEntity;
import com.yboot.module.quartz.model.query.SysJobQuery;
import com.yboot.module.quartz.model.vo.SysJobDetailVo;
import com.yboot.module.quartz.model.vo.SysJobVo;
import com.yboot.module.quartz.service.ISysJobService;
import com.yboot.starter.common.core.web.vo.Result;
import com.yboot.starter.mybatis.core.base.controller.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import org.quartz.SchedulerException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务调度表
 *
 * @author yangcs
 * @date 2025-08-29
 */
@RestController
@RequestMapping("/api/sysJob")
public class SysJobController extends BaseController<ISysJobService, SysJobEntity, SysJobVo, SysJobDetailVo, SysJobQuery, SysJobDto> {

    /**
     * 分组列表
     */
    @GetMapping("group")
    public Result<List<String>> group() {
        List<SysJobEntity> list = baseService.list(Wrappers.<SysJobEntity>lambdaQuery()
                .select(SysJobEntity::getJobGroup)
                .groupBy(SysJobEntity::getJobGroup));
        List<String> groups = list.stream().map(SysJobEntity::getJobGroup).collect(Collectors.toList());
        return Result.ok(groups);
    }


    /**
     * 立即运行一次
     */
    @PostMapping("run-once")
    public Result<Boolean> runOnce(@RequestParam String jobId) {
        try {
            return Result.ok(baseService.run(jobId));
        } catch (SchedulerException e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "暂停")
    @PostMapping("pause")
    public Result pause(@RequestParam String jobId) {
        try {
            return Result.ok(baseService.pauseJob(jobId));
        } catch (SchedulerException e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "恢复")
    @PostMapping("resume")
    public Result<Boolean> resume(@RequestParam String jobId) {
        try {
            return Result.ok(baseService.resumeJob(jobId));
        } catch (SchedulerException e) {
            return Result.error(e.getMessage());
        }
    }

}
